package edu.jhu.secondhome.database.accessors;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import edu.jhu.secondhome.database.ConnectionPool;
import edu.jhu.secondhome.database.DataUtil;

/**
 * This is a utility class that the other DB Accessors extend so they will all have 
 * this method; executeQuery() methods could not be done the same way since the 
 * ResultSet will close when the statement is closed and the results will not be 
 * able to be parsed unless it's done right there.
 */
public class Accessor {
	
	/**
	 * This method is used to run INSERT, UPDATE, and DELETE queries that 
	 * require the executeUpdate() method to be called on the prepared 
	 * statement
	 * @param sql - the SQL statement to run
	 * @param params - the parameters to substitute
	 * @return int - the integer returned by the prepared statement executeUpdate() method
	 * @throws SQLException 
	 */
	public int executeUpdateStatement(final String sql, final Object[] params) throws SQLException {
		final ConnectionPool pool = ConnectionPool.getInstance();
		final Connection conn = pool.getConnection();
		PreparedStatement ps = null;
		
		try {
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				ps.setObject((i+1), params[i]);
			}
			return ps.executeUpdate();
		} finally {
			DataUtil.closeStatement(ps);
			pool.freeConnection(conn);
		}
	}
	
}
